/*
 * IfInstruction.java
 * 
 * last update: 01.02.2010 by Florea Mihai
 * 
 * author:	Power(power@kermit.cs.pub.ro)
 * 			Florea Mihai(florea.mihai@gmail.com)
 * 
 * Obs: Am adaugat @SuppressWarnings("serial").
 */

package engine;

@SuppressWarnings("serial")
class IfInstruction extends DefaultInstruction{
	Expression cond;
	DefaultInstruction iTrue, iFalse;

	IfInstruction(NameSpace ns, int db, InstructionDescription desc,
			Expression e, DefaultInstruction iT, DefaultInstruction iF,
			DefaultInstruction next){
		super(ns, db, desc);
		cond = e;
		iTrue = iT;
		iFalse = iF;
		if (iT != null)
			iTrue.append(this);
		if (iF != null)
			iFalse.append(this);
		add(next);
	}
	public Instruction next() {
		switch (state) {
		case 0:
			return next;
		case 1:
			if (iTrue != null)
				return iTrue;
			else return next;
		case 2:
			if (iFalse != null)
				return iFalse;
			else return next;
		}
		throw new Error("illegal instruction state");
	}

	public void execute()
	throws InterpretTimeException, SimulationStoppedException
	{
		switch (state) {
		case 0:
			waitToRun();
			boolean tmp;
			try{
				tmp = cond.evaluate().isTrue();
			}catch(InterpretTimeException ex){
				xConsole.dumpStack(ex);
				throw new InterpretTimeException(desc + ": error:" + ex);
			}
			xConsole.debug(toString() + (tmp ? "" : "skipping"));

			if (tmp) state = 1;
			else state = 2;
			break;
		case 1:
		case 2:
			state = 0;
		}
	}

}
